import { encryptAES,decryptAES } from './crypto'
import { BASEURL } from './host.js'
const {logs} = require('@/utils/logs.js');

// 请求头判断
import { headers } from '@/utils/headers.js'
// const host = window.location.host;
// var protocol = document.location.protocol;
const BASE_URL = BASEURL(false);

// 判断是否AES加密
const isAES = (options)=>{
	const {type,params} = options;
	switch(type){
		case 1:
			return  { 'request': params } //普通post请求
		case 2:
		case 3:
			return params || {} //普通get请求
		default:
			return { 'req': encryptAES(params) } //post请求 AES加密
	}
}

//请求类
// DEFAULTURL   为true表示不需要BASE_URL
// ISTOKEN      为false表示不需要添加header
// type         表示请求类型
export const myRequest = (options) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: !options.DEFAULTURL ? BASE_URL + options.url : options.url,
			header: headers(options),
			method: options.methods || "POST",
			data: isAES(options) ,
			sslVerify: false,
			timeout: 60000,
			dataType: options.dataType || "json",
			success: (res) => {
				uploadLogs(options,res)
				const { code, msg, data } = res.data;
				if (code === 2000) {
					return options.type===1 || options.type===3 ? resolve(res.data) :  resolve({code,data:decryptAES(data),msg})
				} else {
					logs({
						apiUrl: !options.DEFAULTURL ? BASE_URL + options.url : options.url,
						data: options,
						aesData:isAES(options),
						result:res
					},'error')
					switch(code){
						case -91002://业务验证错误
						case -91003://令牌错误
							uni.removeStorageSync('VMSATOKEN')
							uni.showToast({
								title: '登录失效',
								icon: 'none'
							});
							uni.switchTab({
								url: '/jvss/pages/cloud/cloud'
							});
							return resolve(res.data)
							// 退出登录
							break;
						case -91004://公共秘钥错误，请重新登录
							uni.removeStorageSync('VMSATOKEN')
							return resolve(res.data)
							// 退出登录
							break;
						default:
						return resolve(res.data)
					}	
				}
			},
			fail: (err) => {
				reject(err)
			}
		})
	})
}

// 小程序等其他接口请求
export const otherRequest = (options) => {
	const{url,header,methods,params,dataType} = options;
	return new Promise((resolve, reject) => {
		uni.request({
			url,
			header,
			method: methods || "POST",
			data: params,
			sslVerify: false,
			timeout: 60000,
			dataType: dataType || "json",
			success: (res) => {
				// console.log('请求',res)
				uploadLogs(options,res,'other')
				let datas = JSON.parse(res.data);
				// const { code, msg, data } = datas;
				return resolve(datas)
			},
			fail: (err) => {
				reject(err)
			}
		})
	})
}

//上传离线日志
const uploadLogs = (opt,result,type)=>{
	// #ifdef MP-WEIXIN
	logs({
		apiUrl: !opt.DEFAULTURL ? BASE_URL + opt.url : opt.url,
		requestData:type =='other'?opt.params:isAES(opt),
		result: result
	},'info',false)
	// #endif
}
	